package airport.user.action;

import airport.user.dao.UserDAO;

import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;  
import org.apache.struts2.interceptor.ServletResponseAware; 

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements ServletResponseAware, ServletRequestAware  {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String emailaddress;
	private String passwordlogin;
	private String username = null;
	
	protected HttpServletResponse servletResponse;  
	@Override   
	public void setServletResponse(HttpServletResponse servletResponse) {   
		this.servletResponse = servletResponse;   
	}   
	
	protected HttpServletRequest servletRequest;   
	@Override   
	public void setServletRequest(HttpServletRequest servletRequest) {   
		this.servletRequest = servletRequest;   
	} 
	
	
	public String execute() {
		System.out.println("email:"+getEmailaddress());
		System.out.println("password:"+getPasswordlogin());
		//add cookies
		UserDAO dao = new UserDAO();
		username = dao.findUsernameByEmail(emailaddress);
		System.out.println(username);
		Cookie cookie = new Cookie("AirportUser", username);  
		cookie.setMaxAge(60*60*24*365); // Make the cookie last a year  
		servletResponse.addCookie(cookie); 
		return "success";
	}
	
	public void validate() {
		UserDAO dao = new UserDAO();
		String pw = dao.findPasswordByEmail(emailaddress);
		if (emailaddress == null || passwordlogin == null) {
			addFieldError("emailaddress","email & password cannot be empty");
		}
		else
			if (pw == null || ((passwordlogin != null)&&(!passwordlogin.equals(pw)))) {
				addFieldError("emailaddress","invalid email or password");
			}
	}

	public String getEmailaddress() {
		return emailaddress;
	}

	public void setEmailaddress(String emailaddress) {
		this.emailaddress = emailaddress;
	}

	public String getPasswordlogin() {
		return passwordlogin;
	}

	public void setPasswordlogin(String passwordlogin) {
		this.passwordlogin = passwordlogin;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}

}
